


$().ready(function(){

	// public data

	// chart datas 


    var option_pie = {
        tooltip: {
            trigger: 'item',
            formatter: "{d}%"
        },
        colors:[],

        series: [
            {
                name:'年龄段',
                type:'pie',
                radius: ['80%', '100%'],
                // avoidLabelOverlap: false,
                label: {
                    normal: {
                       formatter: "{d}%",
                       position: "inner"

                    }
                },
                labelLine: {
                    normal: {
                        show: false
                    }
                },
                data:[
                    {value:335, name:'25岁以下'},
                    {value:310, name:'26~30岁'},
                    {value:234, name:'31~35岁'},
                    {value:135, name:'36~40岁'},
                    {value:548, name:'41~45岁'},
                    {value:123, name:'45岁以上'}

                ]
            }
        ]
    };



    var option_height = {
        
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        grid: {
            bottom: '25%'
        },

        legend: {
            data:['人数','占比'],
            left: 'center',
            bottom: 0
        },
        xAxis: [
            {
                type: 'category',
                axisTick: {
                    alignWithLabel: true
                },
                axisLabel: {
                    rotate: 25
                },
                data: ['155cm以下','156~160cm','161~165cm','166~170cm','171~175cm','176~180cm','180cm以上']
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '人数',
                min: 0,
                position: 'left',
                axisLabel: {
                    formatter: '{value}'
                }
            },
            {
                type: 'value',
                name: '占比',
                min: 0,
                position: 'right',
                axisLabel: {
                    formatter: '{value}%'
                },
                splitLine: {
                    show: false
                }
            }
        ],
        series: [
            {
                name:'人数',
                type:'bar',
                barCategoryGap: '70%',
                itemStyle:{
                    normal:{
                        color: 'steelblue'
                    }
                },
                label: {            
                    normal: {
                       show: true, 
                       formatter: "{c}",
                       position: "inside",
                       color: 'black'
                    }
                },
                data:[]
            },
            {
                name:'占比',
                type:'line',
                itemStyle:{
                    normal:{
                        color: 'darkorange',
                    }
                },
                label: {
                    normal: {
                       show: true, 
                       formatter: "{c}%",
                       position: "top",


                    }
                },
                yAxisIndex: 1,
                data:[]
            }
        ]
    };



    var option_weight = {
        
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        grid: {
            bottom: '25%'
        },

        legend: {
            data:['人数','占比'],
            left: 'center',
            top: 'bottom'
        },
        xAxis: [
            {
                type: 'category',
                axisTick: {
                    alignWithLabel: true
                },
                axisLabel: {
                    rotate: 25
                },
                splitLine: {
                    show: true
                },
                data: ['45kg以下','46~50kg','51~55kg','56~60kg','61~65kg','66~70kg', '71~75kg', '76以上']
            }
        ],
        yAxis: [
            {
                type: 'value',
                name: '人数',
                min: 0,
                position: 'left',
                axisLabel: {
                    formatter: '{value}'
                },
                
                splitLine: {
                    show: false
                }
            },
            {
                type: 'value',
                name: '占比',
                min: 0,
                position: 'right',
                axisLabel: {
                    formatter: '{value}%'
                },
                
                splitLine: {
                    show: false
                }
            }
        ],
        series: [
            {
                name:'人数',
                type:'line',
                itemStyle:{
                    normal:{
                        color: 'steelblue'
                    }
                },
                label: {
                    normal: {
                        show: true,
                       formatter: "{c}",
                       position: "bottom",
                       color: 'black'

                    }
                },
                data:[]
            },
            {
                name:'占比',
                type:'line',
                itemStyle:{
                    normal:{
                        color: 'darkorange'
                    }
                },
                label: {
                    normal: {
                        show: true,
                       formatter: "{c}%",
                       position: "top",
                       color: 'darkorange'

                    }
                },
                yAxisIndex: 1,
                data:[]
            }
        ]
    };

	var all_data_count = 0
	var data = [];
    console.log("i can do it")

    

	// $("datalist#gymName").append("<option value='全国'>");
	$.post(dataDomain + "aj/curd.php", {table: "gym", do: "select", fields: "distinct city", conditions: JSON.stringify({status: 1})}, function(r){
		console.log(r)
		var s = JSON.parse(r);
		for(var i in s){
			var x = s[i];
			var op = $("<option>")
			op.val(x.city);
			$("datalist#gymName").append(op);
		}
		$.post(dataDomain +　"aj/curd.php", {table: "gym", do: "select", fields: "name", conditions: JSON.stringify({status: 1})}, function(r){
			// console.log(r)
			var s = JSON.parse(r);
			for(var i in s){
				var x = s[i];
				var op = $("<option>")
				op.val(x.name);
				$("datalist#gymName").append(op);
			}
		})
	})	


	$("button#btn_gymName").click(function(){
		var gymName = $("input[name=gymName]").val();
		if(! gymName){
			alert ("请选择门店！");
			return ;
		}
		$("article.charts").show();
		
		// console.log(gymName);
		$.post(dataDomain + "aj/getUser.php", {gymName: gymName}, function(r){
			console.log(r)
			data = JSON.parse(r);
			all_data_count = data.length;
			$("span.all_users").html("(共有学员" + all_data_count + "人)" );
			// console.log("s.length=" + s.length);

			// 处理第一图，用户性别比

			// 统计男女性别人数
			var sex = {male: 0, female: 0, norecord: 0};
			for(var i in data){
				var x = data[i];
				if(x.sex == 1){
					sex.male ++;
				}else if(x.sex == 2){
					sex.female ++;
				}else{
					sex.norecord ++;
				}
			}

			console.log(sex);
			// console.log("data.length=" + data.length);

			$("section.userSex").find("#male_percent").html("男性：" + Math.round(sex.male / (sex.male + sex.female) * 100) + "%");
			$("section.userSex").find("#female_percent").html("女性：" + Math.round(sex.female / (sex.male + sex.female) * 100) + "%");
			$("section.userSex").find(".first_percent").css("width", Math.round(sex.male / (sex.male + sex.female) * 100) + "%");
			$("section.userSex").find("#male_count").html(sex.male  + "人");
			$("section.userSex").find("#female_count").html(sex.female  + "人");


			// 处理第二图，用户bmi分布
			var bmi = [0, 0, 0, 0];
			for(var i in data){
				var x = data[i];
				var b = Math.ceil(x.weight / x.height / x.height * 100000);
				// console.log(b)
				if(b){
					if(b <= 184){
						bmi[0] ++ ;
					}else if(b <= 239){
						bmi[1] ++ ;
					}else if(b <= 279){
						bmi[2] ++ ;
					}else{
						bmi[3] ++
					}
				}
			}

			console.log(bmi)
			
			$("section.userBMI").find("#bmi1").html(bmi[0] + '人');
			$("section.userBMI").find("#bmi2").html(bmi[1] + '人');
			$("section.userBMI").find("#bmi3").html(bmi[2] + '人');
			$("section.userBMI").find("#bmi4").html(bmi[3] + '人');
			var goodbmi = bmi[0] + bmi[1] + bmi[2] + bmi[3];  // bmi值有效的总人数
			$("section.userBMI").find("#bmir1").html("占比：" + Math.round(bmi[0] / goodbmi * 100) + '%');
			$("section.userBMI").find("#bmir2").html("占比：" + Math.round(bmi[1] / goodbmi * 100) + '%');
			$("section.userBMI").find("#bmir3").html("占比：" + Math.round(bmi[2] / goodbmi * 100) + '%');
			$("section.userBMI").find("#bmir4").html("占比：" + Math.round(bmi[3] / goodbmi * 100) + '%');


			// 处理第三图，用户年龄分布

			var age = [0,0,0,0,0,0];

			for(var i in data){
				var x = data[i];
				var a = x.age
				if(! a && x.birthday){
					// 没有年龄但是有生日的，将生日换算成年龄
					a = 2018 - new Date(Date.parse(x.birthday)).getFullYear();
				}
				if(a){
					if(a <= 25) {
						age[0] ++ ;
					}else if(a <= 30){
						age[1] ++ ;
 					}else if(a <= 35){
 						age[2] ++ ;
 					}else if(a <= 40){
 						age[3] ++ ;
 					}else if(a <= 45){
 						age[4] ++ ;
 					}else {
 						age[5] ++ ;
 					}
				}
			}
			console.log(age);
			for(var i = 0; i < 6; i++){
				option_pie.series[0].data[i].value = age[i];
			}
			var i = 0;
			$("section.userAge .chart_data_d div").each(function(){
				$(this).html(age[i] + "人");
				i ++;
			})


			// 处理第四图，用户身高分布
			var height = [0,0,0,0,0,0,0];
			var heightR = [];
			var goodheight = 0
			for(var i in data){
				var h = data[i].height;
				if(h){
					if(h <= 155){
						height[0] ++ ;
					}else if(h <= 160){
						height[1] ++ ;
					}else if(h <= 165){
						height[2] ++ ;
					}else if(h <= 170){
						height[3] ++ ;
					}else if(h <= 175){
						height[4] ++ ;
					}else if(h <= 180){
						height[5] ++ ;
					}else{
						height[6] ++ ;
					}
					goodheight ++;
				}
			}
			console.log(height);
			option_height.series[0].data = height;
			for (var i = 0; i < 7; i ++){
				heightR[i] = Math.round(height[i] / goodheight * 100);
			}
			option_height.series[1].data = heightR;

			// 处理第五图，用户体重分布
			var weight = [0,0,0,0,0,0,0,0];
			var weightR = [];
			var goodweight = 0;
			for (var i in data){
				var w = data[i].weight;
				if(w){
					if(w <= 45){
						weight[0] ++ ;
					}else if(w <= 50){
						weight[1] ++ ;
					}else if(w <= 55){
						weight[2] ++ ;
					}else if(w <= 60){
						weight[3] ++ ;
					}else if(w <= 65){
						weight[4] ++ ;
					}else if(w <= 70){
						weight[5] ++ ;
					}else if(w <= 75){
						weight[6] ++ ;
					}else {
						weight[7] ++ ;
					}
					goodweight ++;
				}
			}
			console.log(weight);
			option_weight.series[0].data = weight;
			for(var i = 0; i < 8; i ++){
				weightR[i] = Math.round(weight[i] / goodweight * 100);
			}
			option_weight.series[1].data = weightR

			echarts.init(document.getElementById('userAge')).setOption(option_pie);
			echarts.init(document.getElementById("userHeight")).setOption(option_height);
			echarts.init(document.getElementById("userWeight")).setOption(option_weight);

			// 所有显示都完成之后，再显示门店名称，以保持显示名称与数据统一
			$("span.gymName").html(gymName);
		})
		
		
	})

	// $("input[name=gymName]").keyup(function(event){
	// 	// console.log(event.keyCode);
	// 	if(event.keyCode == 13){
	// 		$("button#btn_gymName").triggle("click");
	// 	}
	// })

})